package com.success.task.web.servlet.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.tuckey.web.filters.urlrewrite.utils.Log;

import com.success.task.web.exceptions.LuceneException;
import com.success.task.web.lucene.interfaces.SearcherInterface;
import com.success.task.web.utils.StringUtil;

@Controller
public class Search {
	
	private Log log =  Log.getLog(Search.class);
	@Autowired
	private SearcherInterface defaultIndexSearcher = null;
	
	@RequestMapping("/search.go")
	public ModelAndView search(HttpServletRequest request,HttpServletResponse response,  
            ModelMap modelMap) {
		
		String keywords = StringUtil.ensureEncoding(request.getParameter("t_w_i_n_s"));
		int page = StringUtil.getInt(request.getParameter("t_w_i_n_p"));
		keywords = StringUtil.substring(keywords);
		if(null != keywords&&!keywords.equals("")) {
			keywords = StringUtil.deleteSpaceChars(keywords);
			try {
				modelMap.put("results",defaultIndexSearcher.search(keywords,page));
			} catch (LuceneException e) {
				log.error(e);
				e.printStackTrace();
			}
			modelMap.put("t_w_i_n_s", keywords);
			modelMap.put("t_w_i_n_p", page);
		}
		return new ModelAndView("search",modelMap);
	}

	public void setDefaultIndexSearcher(SearcherInterface defaultIndexSearcher) {
		this.defaultIndexSearcher = defaultIndexSearcher;
	}

}
